<template>
  <div id="special-list">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <!-- <Col class="search-item">
          <span class="search-label">订单状态:</span>
          <Select v-model="searchObj.orderStatus" @on-change="doSearch">
            <Option v-for="item in orderStatus" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">支付方式:</span>
          <Select v-model="searchObj.payCode" @on-change="doSearch">
            <Option v-for="item in payMethod" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col> -->
          <Col class="search-item">
          <span class="search-label">支付流水号:</span>
          <Input v-model="searchObj.transactionId"
                 placeholder="请输入"
                 :maxlength="100">
          </Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">订单编号:</span>
          <Input v-model="searchObj.orderCode"
                 placeholder="请输入">
          <!-- <Icon type="ios-search" slot="suffix"  @click="doSearch"/> -->
          </Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">订单类型:</span>
          <Select v-model="searchObj.orderType"
                  @on-change="doSearch">
            <Option v-for="item in orderType"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="doSearch(2)">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="clearSearch">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item">
          <Button v-if="exampleShow"
                  @click="exampleOpen">收起筛选
            <Icon type="ios-arrow-down" />
          </Button>
          <Button v-else
                  @click="exampleOpen">更多筛选
            <Icon type="ios-arrow-up" />
          </Button>
          </Col>
        </Row>
      </Row>
      <div class="search-example"
           v-show="exampleShow">
        <Row type="flex">
          <Col class="search-item">
          <span class="search-label">门店名称:</span>
          <Select v-model="searchObj.shopId"
                  :max-tag-count="1"
                  :max-tag-placeholder="maxTagPlaceholder"
                  placeholder="请输入"
                  filterable
                  multiple
                  class="select-shop-item"
                  @on-change="doSearch">
            <Option v-for="item in shopListData"
                    :value="item.shopId"
                    :key="item.shopId">{{ item.shopName }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">创建时间:</span>
          <Poptip placement="bottom-end"
                  trigger="hover"
                  content="查询间隔时间最大为7天">
            <DatePicker ref="creationTime"
                        v-model="dateTimes"
                        :editable="false"
                        @on-change="dateChange"
                        format="yyyy-MM-dd HH:mm:ss"
                        placement="bottom"
                        type="datetimerange"
                        :options='dateRangeDisabledOptions'
                        @on-clear='clearDatePicker'
                        @on-clickoutside='clickoutside'>
            </DatePicker>
          </Poptip>
          </Col>
        </Row>
      </div>
    </div>
    <Table :loading="loading"
           :height="this.tableHeight"
           ref="selection"
           :columns="columns"
           :data="orderList.specialOrderData"
           stripe
           class="table-list"
           @on-selection-change="onSelectionChange">
      <!-- 订单状态 -->
      <template slot-scope="{ row }"
                slot="orderStatus">
        <span>{{ row.orderStatus==="0"?"待付款":row.orderStatus==="1"?"待发货":row.orderStatus==="2"?"待收货":row.orderStatus==="3"?"已完成":row.orderStatus==="4"?"已取消":"" }}</span>
      </template>
      <!-- 订单类型 -->
      <template slot-scope="{ row }"
                slot="orderType">
        <span>{{ row.orderType==="3"?"游戏币订单":row.orderType==="4"?"游戏券订单":row.orderType==="5"?"游戏卡订单":row.orderType==="6"?"休闲项目订单":row.orderType==="7"?"商品订单" :row.orderType==="8"?"礼品订单":row.orderType==="9"?"团购订单":row.orderType==="10"?"兑换券订单":row.orderType==="11"?"办卡押金订单":row.orderType==="12"?"手工或导入订单" :row.orderType==="13"?"其他订单":row.orderType==="14"?"新项目订单":row.orderType==="15"?"商铺租赁订单":row.orderType==="16"?"废品收入订单":row.orderType==="17"?"租赁押金订单":row.orderType==="18"?"机台租赁":row.orderType==="19"?"会员补卡":row.orderType==="20"?"特殊团购订单":row.orderType==="21"?"游戏券套餐":"" }}</span>
      </template>
      <!-- 支付方式 -->
      <template slot-scope="{ row }"
                slot="payCode">
        <span>{{ row.payCode==="ALIPAY"?"支付宝支付":row.payCode==="WEIXIN"?"微信支付":row.payCode==="CASH"?"现金支付":row.payCode==="UNION"?"银联支付":row.payCode==="TRANSFER_TO_PUBLIC_ACCOUNT"?"对公转账":row.payCode==="INTEGRAL"?"积分":row.payCode==="TICKET"?"彩票":row.payCode==="CURRENCY"?"游戏币":"" }}</span>
      </template>
      <!-- 租金 -->
      <template slot-scope="{ row }"
                slot="incomeAmount">
        <span>{{ row.incomeAmount?row.incomeAmount:"0.00" }}</span>
      </template>
      <!-- 押金 -->
      <template slot-scope="{ row }"
                slot="depositAmount">
        <span>{{ row.depositAmount?row.depositAmount:"0.00" }}</span>
      </template>
      <!-- 其他金额 -->
      <template slot-scope="{ row }"
                slot="otherAmount">
        <span>{{ row.otherAmount?row.otherAmount:"0.00" }}</span>
      </template>
      <!-- 到期返还金额 -->
      <template slot-scope="{ row }"
                slot="returnAmount">
        <span>{{ row.returnAmount?row.returnAmount:"0.00" }}</span>
      </template>
      <template slot-scope="{ row, index }"
                slot="action">
        <!-- <i v-if="row.orderStatus == 3 &&(row.orderType == 15 || row.orderType == 17 || row.orderType == 18)" class="iconsys icontuikuan" title="退款" @click='refund(row, index)'></i> -->
        <i v-if="row.orderStatus === '3' && beforeOneYearOrder(row.createTime) && (row.orderType === '15' || row.orderType === '18' || row.orderType === '20')"
           class="iconsys icontuikuan"
           title="退款"
           @click='refund(row, index)'></i>
      </template>
    </Table>
    <div class="page-box"
         style="margin-top: 20px">
      <Page :total="orderList.specialOrderTotal"
            :current.sync="searchObj.pageIndex"
            :page-size="searchObj.pageSize"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            show-total />
    </div>
    <Spin size="large"
          fix
          v-if="spinShow"></Spin>
    <Modal v-model="refundModel"
           title="退款"
           :mask-closable="false"
           :closable="false">
      <p>确认要对此订单进行退款操作？</p>
      <div slot="footer">
        <Button :disabled="loadingModel"
                type="text"
                size="large"
                @click="asyncCancel">取消</Button>
        <Button type="primary"
                size="large"
                :loading="loadingModel"
                :disabled="loadingModel"
                @click="asyncOK">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { specialOrderQuery, specialOrderRefund } from '@/api/order/index'
import { getShopList } from '@/api/system/store'
import { formatDate } from '@/libs/tools'
import myMixin from '@/mixins/dateRangePicker'
export default {
  name: 'order_special_list',
  mixins: [myMixin],
  data () {
    return {
      shopId: '',
      spinShow: false,
      exampleShow: true,
      loading: true,
      loadingModel: false,
      refundModel: false,
      tableHeight: 0,
      // 订单状态
      orderStatus: [
        { value: -1, label: '全部' },
        { value: 0, label: '待付款' },
        { value: 3, label: '已完成' }
      ],
      orderType: [
        { value: -1, label: '全部' },
        { value: 14, label: '新项目订单' },
        { value: 15, label: '商铺租赁订单' },
        { value: 18, label: '机台租赁订单' },
        { value: 17, label: '押金订单' },
        { value: 20, label: '特殊团购订单' }
      ],
      dateTimes: [
        formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      ],
      // 支付方式
      payMethod: [
        { value: -1, label: '全部' },
        { value: 'WEIXIN', label: '微信支付' },
        { value: 'ALIPAY', label: '支付宝支付' },
        { value: 'UNION', label: '银联支付' },
        { value: 'CASH', label: '现金支付' },
        { value: 'TRANSFER_TO_PUBLIC_ACCOUNT', label: '对公转账' }
      ],
      // 表格列名称
      columns: [
        { title: '订单编号', key: 'orderCode', minWidth: 170, fixed: 'left' },
        // { title: '父订单编号', key: 'parentOrderCode', minWidth: 200 },
        // { title: '订单状态', slot: 'orderStatus', minWidth: 150 },
        { title: '订单类型', slot: 'orderType', minWidth: 150 },
        { title: '门店名称', key: 'shopName', minWidth: 150 },
        // { title: '门店ID', key: 'shopId', minWidth: 300 },
        { title: '团购/租赁商户名称', key: 'rentMerchantName', minWidth: 200, tooltip: true },
        { title: '顾客姓名', key: 'customerName', minWidth: 150 },
        { title: '开始时间', key: 'beginTime', minWidth: 200 },
        { title: '结束时间', key: 'endTime', minWidth: 200 },
        { title: '租金(元)', slot: 'incomeAmount', minWidth: 150 },
        { title: '押金(元)', slot: 'depositAmount', minWidth: 150 },
        { title: '进场费(元)', slot: 'otherAmount', minWidth: 150 },
        { title: '新项目利率(%)', key: 'storeCardAmountRate', minWidth: 150 },
        { title: '订单总金额(元)', key: 'totalAmount', minWidth: 150 },
        { title: '到期返还金额(元)', slot: 'returnAmount', minWidth: 150 },
        { title: '支付方式', slot: 'payCode', minWidth: 120 },
        { title: '创建时间', key: 'createTime', minWidth: 200 },
        { title: '操作', slot: 'action', width: 80, fixed: 'right' }
      ],
      searchTime: {
        timeBegin: formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        timeEnd: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      },
      orderCode: '',
      searchObj: {
        orderCode: '',
        transactionId: '',
        orderStatus: -1,
        shopId: [],
        payCode: -1,
        orderType: -1,
        creationTime: [
          formatDate(
            new Date(new Date().getTime() - 86400000 * 7),
            'yyyy-MM-dd hh:mm:ss'
          ),
          formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
        ],
        pageIndex: 1,
        pageSize: 10
      },
      orderList: {
        specialOrderData: [],
        specialOrderTotal: 0
      },
      shopListData: ''
    }
  },
  mounted () {
    this.selectDateRangeDisabled(this.$refs.creationTime, 7)
  },
  created () {
    this.getShopListLoad()
  },
  methods: {
    // 判断订单是否是一年之前的订单
    beforeOneYearOrder (time) {
      let pre = new Date()
      pre.setFullYear(pre.getFullYear() - 1)
      if (pre.getTime() - new Date(time).getTime() > 0) {
        return false
      } else {
        return true
      }
    },
    maxTagPlaceholder (num) {
      return '...'
    },
    getShopListLoad () {
      this.tableHeight = 0
      this.loading = true
      getShopList({
        permissionCode: 'moms:order:special', // 查看特殊订单
        merchantId: this.$store.state.user.merchantId,
        offset: 0,
        limit: 99999
      })
        .then(res => {
          if (res.data.status === 200) {
            if (res.data.totalCount > 0) {
              this.shopListData = res.data.data
              // let shopId = res.data.data[0].shopId
              // this.searchObj.shopId.push(shopId)
              this.getSpecialOrderload()
            } else {
              this.orderList.specialOrderData = []
              this.orderList.specialOrderTotal = 0
              this.loading = false
            }
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
        .catch(error => {
          this.$Message.error(`${this.showError(error)}`)
          this.loading = false
        })
    },
    getSpecialOrderload () {
      this.tableHeight = 0
      // if (this.searchObj.shopId.length > 0) {
      this.loading = true
      let params = {
        transactionId: this.searchObj.transactionId, //  支付流水号
        orderCode: this.orderCode, //  订单编号
        merchantId: this.$store.state.user.merchantId, // 商户id
        // orderStatus: this.searchObj.orderStatus !== -1 ? this.searchObj.orderStatus : '',
        shopId:
          this.searchObj.shopId.length > 1
            ? this.searchObj.shopId.join(',')
            : this.searchObj.shopId.join(''), // 门店ID
        // payCode: this.searchObj.payCode !== -1 ? this.searchObj.payCode : '',
        orderType:
          this.searchObj.orderType !== -1 ? this.searchObj.orderType : '',
        offset: (this.searchObj.pageIndex - 1) * this.searchObj.pageSize, // 分页OFFSET
        limit: this.searchObj.pageSize
      }
      if (this.searchObj.creationTime) {
        params.createTimeBegin = this.searchObj.creationTime[0]
        params.createTimeEnd = this.searchObj.creationTime[1]
      }
      specialOrderQuery(params)
        .then(res => {
          if (res.data.status === 200) {
            this.orderList.specialOrderData = res.data.data
            this.orderList.specialOrderTotal = res.data.totalCount
            this.loading = false
            if (res.data.data && res.data.data.length >= 10) {
              this.tableHeight = 537
            }
          } else {
            this.$Message.error(res.data.error)
            this.loading = false
          }
        })
        .catch(error => {
          this.$Message.error(`${this.showError(error)}`)
          this.loading = false
        })
      // }
    },
    orderRefundOperate () {
      this.loadingModel = true
      specialOrderRefund({
        orderCode: this.orderCode,
        shopId: this.shopId
      })
        .then(res => {
          if (res.data.status === 200) {
            setTimeout(() => {
              this.refundModel = false
              this.$Message.success('退款成功！')
              this.loadingModel = false
              this.shopId = ''
              this.orderCode = ''
              this.getSpecialOrderload()
            }, 3000)
          } else {
            this.loadingModel = false
            this.$Message.error('退款失败！')
          }
        })
        .catch(error => {
          this.loadingModel = false
          this.$Message.error('退款失败！' + `${this.showError(error)}`)
        })
    },
    refund (row) {
      this.orderCode = row.orderCode
      this.shopId = row.shopId
      this.refundModel = true
    },
    asyncOK () {
      this.loadingModel = true
      this.orderRefundOperate()
    },
    asyncCancel () {
      this.orderCode = ''
      this.shopId = ''
      this.refundModel = false
    },
    handlePage (val) {
      this.searchObj.pageIndex = val
      this.getSpecialOrderload()
    },
    handlePageSize (val) {
      this.searchObj.pageSize = val
      this.searchObj.pageIndex = 1
      this.getSpecialOrderload()
    },
    doSearch (type = 1) {
      // if (this.searchObj.shopId.length > 0) {
      if (type === 2) {
        this.orderCode = this.searchObj.orderCode
        this.searchObj.creationTime = [this.searchTime.timeBegin, this.searchTime.timeEnd]
      }
      this.searchObj.pageIndex = 1
      this.searchObj.pageSize = 10
      this.getSpecialOrderload()
      // } else {
      //   this.orderList.specialOrderData = []
      //   this.orderList.specialOrderTotal = 0
      //   this.$Message.error(`请选择门店！`)
      // }
    },
    clearSearch () {
      this.orderCode = ''
      this.dateTimes = [
        formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      ]
      this.searchTime = {
        timeBegin: formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        timeEnd: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }
      this.searchObj = {
        orderStatus: -1,
        transactionId: '',
        shopId: [],
        payCode: -1,
        orderType: -1,
        creationTime: [
          formatDate(
            new Date(new Date().getTime() - 86400000 * 7),
            'yyyy-MM-dd hh:mm:ss'
          ),
          formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
        ],
        pageIndex: 1,
        pageSize: 10
      }
      this.$refs.creationTime.handleClear()
      // let shopId = this.shopListData[0].shopId
      // this.searchObj.shopId.push(shopId)
      this.loading = true
      this.doSearch()
    },
    dateChange (e) {
      this.searchTime = {
        timeBegin: e[0],
        timeEnd: e[1]
      }
      // this.searchObj.creationTime = e
      // this.getSpecialOrderload()
    },
    onSelectionChange (selection) { },
    exampleOpen () {
      this.exampleShow = !this.exampleShow
    },
    showError (error) {
      return error.response && error.response.data.error
        ? error.response.data.error
        : error.data && error.data.error ? error.data.error : ''
    }
  },
  computed: {}
}
</script>

<style lang='less'>
#special-list {
  .search-box {
    .search-item {
      .ivu-date-picker {
        width: 280px;
        .ivu-date-picker-editor {
          width: 280px;
        }
      }
    }
  }
  .ivu-table-tip {
    span {
      position: absolute;
      width: 100px;
      left: 50%;
      margin-left: -50px;
    }
  }

  .select-shop-item {
    height: 35px;
    width: 210px;
    .ivu-select-selection {
      height: 35px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .ivu-tag {
      max-width: 100px;
    }
  }
  .select-shop-item .ivu-select-dropdown {
    width: 300px;
  }
  .select-shop-item .ivu-select-item {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .select-shop-item .ivu-select-input {
    width: 40px !important;
  }
  .ivu-poptip-body {
    background: #585e6b;
    border-radius: 3px;
    overflow: hidden;
  }
  .ivu-poptip-body-content-inner {
    color: #fff;
  }
  .ivu-poptip-popper[x-placement^='bottom'] .ivu-poptip-arrow:after {
    border-bottom-color: #585e6b;
  }
}
</style>
